const Koa = require("koa");
const Router = require("koa-router");
const { PassThrough } = require("stream");
const cors = require("@koa/cors");

const app = new Koa();
const router = new Router();
app.use(cors());

// SSE 路由处理
router.get("/sse", async (ctx, next) => {
  // 设置响应头
  ctx.set({
    "Content-Type": "text/event-stream",
    "Cache-Control": "no-cache",
    Connection: "keep-alive",
  });
  // 创建流、并作为接口数据进行返回
  const stream = new PassThrough();
  ctx.body = stream;
  ctx.status = 200;

  let timer = setInterval(() => {
    stream.write(`data: ${new Date().toLocaleTimeString()}\n\n`);
  }, 1000);

  ctx.req.on("close", () => {
    console.log("断开连接！");
    clearInterval(timer);
  });
});

app.use(router.routes()).use(router.allowedMethods());

app.listen(3000, () => {
  console.log("server is running at http://localhost:3000");
});
